#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
curl_download () {
    local LOCAL_FILE="$1"
    local URL="$2"
    
    local ALLOW_CONTINUE=${3:-allow}  # default "allow"

    local MIN_SIZE=5242880  # 5MB (1024*1024*5)
    local ONE_MONTH_SECONDS=$((30 * 24 * 60 * 60))  # 30 days in seconds
    local NO_REVOKE_PARAM="--ssl-no-revoke"
    local CONTINUE_PARAM=""

    if [ "$ALLOW_CONTINUE" = "allow" ]; then
        CONTINUE_PARAM="-C -"
    else
        CONTINUE_PARAM=""
    fi

    echo "CONTINUE_PARAM: $CONTINUE_PARAM"

    echo "download $URL"
    if current_os_is_windows; then
        NO_REVOKE_PARAM="--ssl-no-revoke"
    fi

    if [ -f "$LOCAL_FILE" ]; then
        # file size
        local file_size
        # Get file modification time (in seconds)
        local file_mtime
        if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
            file_size=$(stat -f%z "$LOCAL_FILE")
            file_mtime=$(stat -f%m "$LOCAL_FILE")
        else
            file_size=$(stat -c%s "$LOCAL_FILE")
            file_mtime=$(stat -c%Y "$LOCAL_FILE")
        fi
          
        local current_time
        current_time=$(date +%s)

        local age=$((current_time - file_mtime))
        
        echo "current_time=$current_time"
        echo "file_mtime=$file_mtime"
        echo "age=$age"

        # Check if the file size is less than 5MB
        if [ $file_size -lt $MIN_SIZE ]; then
            echo "If the file size is less than 5MB, delete it and download it again."
            rm -f "$LOCAL_FILE"
            CONTINUE_PARAM=""
        # 检查文件是否超过1个月
        elif [ $age -gt $ONE_MONTH_SECONDS ]; then
            echo "If the file hasn't been updated for over 1 month, delete it and download it again."
            CONTINUE_PARAM=""
            rm -f "$LOCAL_FILE"
        else
            echo "The file exists and meets the conditions, attempting resumable transfer."
        fi
    else
        
        echo "The file does not exist, starting download."
        # curl -L -o "$LOCAL_FILE" "$URL"
    fi

    curl -L $CONTINUE_PARAM $NO_REVOKE_PARAM --retry 5 -o "$LOCAL_FILE" "$URL"

}

# param 1: remote url
# param 2: local file path
download_with_resume() {
    local LOCAL_FILE="$1"
    local URL="$2"
    curl_download "$LOCAL_FILE" $URL

    curl_exit=$?

    echo "#1 curl_exit $curl_exit"
    if [ $curl_exit -eq 0 ]; then
        echo "#1 Download completed: $LOCAL_FILE"
        return 0
    else
        echo "#1 Download failed."
        echo "#2 Download again."
        curl_download "$LOCAL_FILE" $URL "not_allow"

        echo "#2 curl_exit $curl_exit"
        if [ $curl_exit -eq 0 ]; then
            echo "#2 Download completed without resume: $LOCAL_FILE"
            return 0
        else
            echo "#2 Download failed."
            return 1
        fi
    fi

    
}

